package com.zhong.other_animation;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.widget.Button;

import com.zhong.main.BaseActivity;
import com.zhong.main.R;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 揭露动画
 */
public class RevealEffectActivity extends BaseActivity {

    @BindView(R.id.tool_bar)
    Toolbar mToolbar;
    @BindView(R.id.view)
    View view;
    @BindView(R.id.btn)
    Button btn;

    private boolean isShow = true;

    public static void startSelf(Context context){
        Intent intent = new Intent(context, RevealEffectActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_reveal_effect;
    }

    @Override
    protected void create() {
        initToolbar();
    }

    private void initToolbar(){
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId() == android.R.id.home){
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    @OnClick(R.id.btn)
    protected void onClick(){
        //计算动画圆形的X坐标，View的宽度 - 按钮宽度的一半 - 按钮右边距
        int centerX = view.getMeasuredWidth() - btn.getMeasuredWidth() / 2 - (view.getMeasuredWidth() - btn.getRight());
        int centerY = view.getMeasuredHeight()  - btn.getMeasuredHeight() / 2;

        //半径计算不精确
        int width = view.getWidth() - btn.getMeasuredWidth() / 2;
        int height = view.getHeight() - btn.getMeasuredHeight() / 2;
        int radius = (int) Math.hypot(width, height); //斜边，半径

        if(isShow){
            Animator animator = ViewAnimationUtils.createCircularReveal(view,centerX, centerY, radius, 0);
            animator.setDuration(1000);
            animator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    view.setVisibility(View.GONE);
                }
            });

            animator.start();
            isShow = false;
        } else{
            //动画前需要把View的可见性设置为Visible
            view.setVisibility(View.VISIBLE);
            Animator animator = ViewAnimationUtils.createCircularReveal(view,centerX, centerY, 0, radius);
            animator.setDuration(1000);
            animator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {

                }
            });

            animator.start();
            isShow = true;
        }
    }
}
